﻿using log4net;
using RemoteData.core;
using RemoteData.utils;
using System;
using System.IO;


namespace RemoteData.model.setting
{
    public class GlobalSetting
    {
        private static ILog logger = LogManager.GetLogger(typeof(GlobalSetting));

        public int listenerPort;

        public GlobalSetting()
        {
            Reset();
        }

        public GlobalSetting(GlobalSetting setting) : this()
        {
            Copy(setting);
        }

        public void Reset()
        {
            listenerPort = 4010;
        }

        public void Copy(GlobalSetting setting)
        {
            this.listenerPort = setting.listenerPort;
        }

        public GlobalSetting Clone()
        {
            return new GlobalSetting(this);
        }

        public int Load()
        {
            int rn = 0;

            string settingFile = TW_App.fileManager.globalSettingFile;
            bool existsFlag = File.Exists(settingFile);
            if (!existsFlag)
            {
                Reset();
                logger.WarnFormat("全局设置文件[{0}]不存在", settingFile);
                return -2;
            }

            GlobalSetting setting = XmlUtil.Load<GlobalSetting>(settingFile);
            if (setting != null)
            {
                //todo:设置变量
                Copy(setting);
                rn = 0;
            }
            else
            {
                Reset();
                logger.ErrorFormat("加载全局设置[{0}]失败", settingFile);
                rn = -3;
            }

            return rn;
        }

        public bool Save()
        {
            String settingFile = TW_App.fileManager.globalSettingFile;

            GlobalSetting globalSetting = new GlobalSetting(this);
            bool rn = XmlUtil.Save<GlobalSetting>(settingFile, globalSetting);
            return rn;
        }
    }
}
